package com.gitee.hljdrl.dsbridge.client;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.content.Context;
import android.content.DialogInterface;
import android.net.Uri;
import android.text.TextUtils;
import android.view.Gravity;
import android.view.View;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.webkit.ConsoleMessage;
import android.webkit.JsPromptResult;
import android.webkit.JsResult;
import android.webkit.PermissionRequest;
import android.webkit.ValueCallback;
import android.webkit.WebChromeClient;
import android.webkit.WebView;
import android.widget.EditText;
import android.widget.FrameLayout;

import com.ffsky.logger.L;
import com.gitee.hljdrl.dsbridge.basis.DSViewEvent;
import com.gitee.hljdrl.dsbridge.basis.WebViewEvent;

public class DSWebChromeClient extends WebChromeClient {

    protected String TAG = "DSWebChromeClient";
    protected WebViewEvent mWebViewEvent;
    //
    private boolean isFullScreen = false;
    private View customView;
    private CustomViewCallback customViewCallback;
    private FrameLayout frameLayout;
    private FrameLayout.LayoutParams layoutParams;
    private DSViewEvent mDSViewEvent;

    public DSWebChromeClient() {

    }

    public DSWebChromeClient(DSViewEvent dsViewEvent, WebViewEvent webViewEvent) {
        this.mWebViewEvent = webViewEvent;
        this.mDSViewEvent = dsViewEvent;
    }

    public boolean isFullScreen() {
        return isFullScreen;
    }

    public void setWebViewEvent(WebViewEvent webViewEvent) {
        mWebViewEvent = webViewEvent;
    }


    @Override
    public void onProgressChanged(WebView view, int newProgress) {
        super.onProgressChanged(view, newProgress);
        if (mDSViewEvent != null) {
            mDSViewEvent.setProgress(newProgress);
        }
    }

    @Override
    public void onPermissionRequest(PermissionRequest request) {
        request.grant(request.getResources());
        L.i(TAG, "onPermissionRequest-->", request.getResources());
    }

    @Override
    public void onReceivedTitle(WebView view, String title) {
        if (TextUtils.equals(title, "网页无法打开")
                || TextUtils.equals(title, "404 Not Found")
                || TextUtils.equals(title, "502 Bad Gateway")) {
            if (mDSViewEvent != null) {
                mDSViewEvent.showError();
            }
            return;
        }
        super.onReceivedTitle(view, title);
    }

    @Override
    public void onConsoleMessage(String message, int lineNumber, String sourceID) {
        L.i(TAG, "console-->", message, "(", sourceID, ":", lineNumber, ")");
    }

    @Override
    public void onShowCustomView(View view, CustomViewCallback callback) {
        L.i(TAG, "onShowCustomView");
        if (mDSViewEvent == null) {
            return;
        }
        // 防止重复显示全屏视图
        try {
            if (customView != null) {
                onHideCustomView();
                return;
            }
            final Activity activity = mDSViewEvent.getActivity();
            // 获取根布局
            FrameLayout rootView = activity.findViewById(android.R.id.content);

            // 设置全屏视图
            customView = view;
            layoutParams = new FrameLayout.LayoutParams(FrameLayout.LayoutParams.MATCH_PARENT, FrameLayout.LayoutParams.MATCH_PARENT);
            frameLayout = new FrameLayout(activity);
            frameLayout.addView(customView, layoutParams);
            rootView.addView(frameLayout, layoutParams);

            // 设置全屏回调
            customViewCallback = callback;
            isFullScreen = true;
            // 其他 UI 调整，如隐藏状态栏等
            activity.getWindow().addFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN);

        } catch (Exception ex) {
            ex.printStackTrace();
        }
    }


    @Override
    public void onHideCustomView() {
        L.i(TAG, "onHideCustomView");
        if (mDSViewEvent == null) {
            return;
        }
        try {
            if (customView == null) {
                return;
            }
            final Activity activity = mDSViewEvent.getActivity();
            // 恢复 UI 设置
            activity.getWindow().clearFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN);

            // 移除全屏视图
            FrameLayout rootView = activity.findViewById(android.R.id.content);
            rootView.removeView(frameLayout);
            customView = null;
            frameLayout = null;
            customViewCallback.onCustomViewHidden();
            customViewCallback = null;
            isFullScreen = false;
        } catch (Exception ex) {
            ex.printStackTrace();
        }

    }

    @Override
    public boolean onJsAlert(WebView view, String url, final String message, final JsResult result) {
        if (mWebViewEvent == null) {
            return super.onJsAlert(view, url, message, result);
        }
        if (!mWebViewEvent.isAlertBoxBlock()) {
            result.confirm();
        }

        Dialog alertDialog = new AlertDialog.Builder(mWebViewEvent.getContext()).
                setMessage(message).
                setCancelable(false).
                setPositiveButton(android.R.string.ok, new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        dialog.dismiss();
                        if (mWebViewEvent.isAlertBoxBlock()) {
                            result.confirm();
                        }
                    }
                })
                .create();
        alertDialog.show();
        return true;
    }

    @Override
    public boolean onJsConfirm(WebView view, String url, String message, final JsResult result) {
        if (mWebViewEvent == null) {
            return onJsConfirm(view, url, message, result);
        }
        if (!mWebViewEvent.isAlertBoxBlock()) {
            result.confirm();
        }

        DialogInterface.OnClickListener listener = new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                if (mWebViewEvent.isAlertBoxBlock()) {
                    if (which == Dialog.BUTTON_POSITIVE) {
                        result.confirm();
                    } else {
                        result.cancel();
                    }
                }
            }
        };
        new AlertDialog.Builder(mWebViewEvent.getContext())
                .setMessage(message)
                .setCancelable(false)
                .setPositiveButton(android.R.string.ok, listener)
                .setNegativeButton(android.R.string.cancel, listener).show();
        return true;


    }

    @Override
    public boolean onJsPrompt(WebView view, String url, final String message, String defaultValue, final JsPromptResult result) {
        if (mWebViewEvent == null) {
            return onJsPrompt(view, url, message, defaultValue, result);
        }

        if (!mWebViewEvent.isAlertBoxBlock()) {
            result.confirm();
        }
        final Context context = mWebViewEvent.getContext();

        final EditText editText = new EditText(context);
        editText.setText(defaultValue);
        if (defaultValue != null) {
            editText.setSelection(defaultValue.length());
        }
        float dpi = context.getResources().getDisplayMetrics().density;
        DialogInterface.OnClickListener listener = new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                if (mWebViewEvent.isAlertBoxBlock()) {
                    if (which == Dialog.BUTTON_POSITIVE) {
                        result.confirm(editText.getText().toString());
                    } else {
                        result.cancel();
                    }
                }
            }
        };
        new AlertDialog.Builder(context)
                .setTitle(message)
                .setView(editText)
                .setCancelable(false)
                .setPositiveButton(android.R.string.ok, listener)
                .setNegativeButton(android.R.string.cancel, listener)
                .show();
        FrameLayout.LayoutParams layoutParams = new FrameLayout.LayoutParams(
                ViewGroup.LayoutParams.MATCH_PARENT,
                ViewGroup.LayoutParams.WRAP_CONTENT);
        int t = (int) (dpi * 16);
        layoutParams.setMargins(t, 0, t, 0);
        layoutParams.gravity = Gravity.CENTER_HORIZONTAL;
        editText.setLayoutParams(layoutParams);
        int padding = (int) (15 * dpi);
        editText.setPadding(padding - (int) (5 * dpi), padding, padding, padding);
        return true;

    }
}
